<template>
  <div class="app-container" ref='consDom'>
    <el-row :gutter="20">
      <!-- left -->
	  <div class="mytree">
	    <el-dialog
	      title="设备选择"
	      :visible.sync="dialogVisible"
	      width="450px"
	      :before-close="handleClose">
	      <div>
			<p>(注：绿色为在线设备，红色为离线设备)</p>
	        <el-input placeholder="设备筛选" v-model="filterText" style='width:290px;'> </el-input>
			<el-button type="info" plain icon="el-icon-search" @click='searchTree' style='margin-left: 10px;'>搜索</el-button>
	        <!-- 树形控件 设备 -->
	  		<el-scrollbar style="height:67vh">
				<el-tree
				  :data="cardList"
				  show-checkbox
				  node-key="id"
				  ref="tree2"
				  :check-on-click-node='true'
				  :default-expanded-keys="expandedKeys"
				  :expand-on-click-node="false"
				  @check="handleShebeiClick"
				  highlight-current
				  :filter-node-method="filterNodes"
				  :props="defaultPropsd"
				  :render-content="renderContent">
				</el-tree>
			</el-scrollbar>
			<div style="background-color: #f1f1f1;font-size: 15px;padding: 10px;display: flex;justify-content: space-around;font-weight: 700;">
				<span>设备总数：{{allDev}}个</span>
				<span>|</span>
				<span >已选择：<span>{{seleteDev}}</span>个</span>
			</div>
	      </div>
	      <span slot="footer" class="dialog-footer">
	        <el-button @click="dialogVisible = false">关闭</el-button>
	        <el-button type="primary" @click="seedDev" :disabled='!dialogVisible'>确定</el-button>
	      </span>
	    </el-dialog>
	  </div>
      <!--right-->
      <el-col :span="24" :xs="24" v-show="isShow" >
		<div ref='colDom' style="position: absolute;height: 100%;"></div>
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          v-if="checkPermi(['lgsv:program:query'])"
        >
          <!-- 节目名称-->
          <el-form-item :label="$t('program.list.label.name')" prop="pTitle">
            <el-input
              v-model="queryParams.pTitle"
              :placeholder="$t('program.list.input.name')"
              clearable
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- 节目ID -->
          <el-form-item :label="$t('program.list.label.id')" prop="pId">
            <el-input
              v-model="queryParams.pId"
              :placeholder="$t('program.list.input.id')"
              clearable
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- 状态 -->
          <!-- <el-form-item label="节目类型" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="全部"
              clearable
              size="small"
              style="width: 100px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="审核状态" prop="status">
            <el-select
              v-model="queryParams.phonenumber"
              placeholder="全部"
              clearable
              size="small"
              style="width: 100px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
          <!-- 创建时间 -->
          <el-form-item :label="$t('program.list.label.time')">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              :start-placeholder="$t('program.list.input.start')"
              :end-placeholder="$t('program.list.input.end')"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <!-- 搜索 -->
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
              >{{ $t('program.list.button.search') }}</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <!-- 新增节目 -->
            <el-button
              type="success"
              plain
              icon="el-icon-folder-add"
              @click="handleUpdateEdit"
              v-hasPermi="['lgsv:program:add']"
              >{{ $t('program.list.button.add') }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <!-- 发送 -->
            <el-button
              type="success"
              plain
              icon="el-icon-upload2"
              :disabled="sendShow"
              @click="handleImport"
              v-hasPermi="['lgsv:program:send']"
              >{{ $t('program.list.button.send') }}</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <!-- 删除 -->
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['lgsv:program:remove']"
            >
              {{ $t('program.list.button.delete') }}
            </el-button>
          </el-col>

          <!-- moveDeviceButton -->
          <el-col :span="1.5">
            <!-- 节目下架 -->
            <el-button
              type="success"
              plain
              icon="el-icon-download"
              :disabled="sendShow"
              v-hasPermi="['lgsv:program:del']"
              @click="handPull"
            >
              {{ $t('program.list.button.down') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- 过期节目 -->
            <el-button
              type="danger"
              plain
              icon="el-icon-pie-chart"
              v-hasPermi="['lgsv:program:expire']"
              @click="handExpire"
            >
              {{ $t('program.list.button.overdue') }}
            </el-button>
          </el-col>
          <!-- editProgran -->
          <!-- <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="sendShow"
              v-hasPermi="['lgsvapi:user:list']"
              >播放列表</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :disabled="sendShow"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col> -->
          <!--  -->
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getProgramList"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <!-- tableData -->
        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
          border
		  v-if='isTable'
          :max-height="tableHeight"
          :row-class-name="tableRowClassName"
          :default-sort="{ prop: 'createTime', order: 'descending' }"
          style="width: 100%"
        >
          <el-table-column type="selection" align="center" />
          <!-- 节目ID -->
          <el-table-column
            :label="$t('program.list.table.pId')"
            align="center"
            key="pId"
            width="80"
            v-if="columns[0].visible">
				<template slot-scope="scope">
					<el-button style='border: 1px solid #d1e9ff;background-color:#e8f4ff;color: #1890ff;padding:5px 10px;' @click="handleProgramId(scope.row)">{{scope.row.pId}}</el-button>
				</template>
		   </el-table-column>
         <!-- 节目号 -->
          <el-table-column
            :label="$t('program.list.table.pNo')"
            align="center"
            key="pNo"
            prop="pNo"
            sortable
            width="85"
            v-if="columns[1].visible"
          />
          <!-- 节目名称 -->
          <el-table-column
            :label="$t('program.list.table.pTitle')"
            align="center"
            key="pTitle"
            prop="pTitle"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <!-- 节目类型 -->
          <el-table-column
            :label="$t('program.list.table.type')"
            align="center"
            width="80"
            key="lgCardType.fDescription"
            prop="lgCardType.fDescription"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <!-- 所属组织 -->
          <el-table-column
            :label="$t('program.list.table.deptName')"
            align="center"
            key="deptName"
            prop="sysDept.deptName"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
          />
          <!-- 播放开始日期 -->
          <el-table-column
            :label="$t('program.list.table.startTime')"
            align="center"
            key="startTime"
            prop="startTime"
            v-if="columns[5].visible"
            width="100"
          />
          <!-- 播放结束日期 -->
          <el-table-column
            :label="$t('program.list.table.endTime')"
            align="center"
            key="endTime"
            prop="endTime"
            v-if="columns[6].visible"
            width="100"
          />
          <!-- 分区数量 -->
          <el-table-column
            :label="$t('program.list.table.area')"
            align="center"
            width="80"
            key="lgProgramAreaList.length"
            prop="lgProgramAreaList.length"
            v-if="columns[7].visible"
          />
          <!-- 节目内容 -->
          <el-table-column
            :label="$t('program.list.table.content')"
            align="center"
            width="100"
            key="phonenumber4"
            show-overflow-tooltip
            v-if="columns[8].visible"
          >
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="left-start">
                <p
                  v-for="(item, index) in scope.row.lgProgramAreaList"
                  :key="index"
                  style="margin-top: 5px;border-bottom: 1px solid gray;display: flex;align-items: center;"
                >
                  <span style="color:red;font-weight:700;display: inline-block"
                    >分区{{ index + 1 }}：</span
                  >
                  <span v-if="item.lgProgramMaterialList[0].mMessage" 
											style="color:dimgray;font-size: 16px;font-weight: 700;max-width:600px;">
                    {{ item.lgProgramMaterialList[0].mMessage }}
                  </span>
                  <span v-for="(items, index) in item.lgProgramMaterialList" :key="index">
                    <span v-if="items.lgFile.fRelativePath">
                      <img :src="items.lgFile.fRelativePath" alt="" />
                    </span>
                  </span>
                </p>
                <div
                  slot="reference"
                  class="name-wrapper"
                  style="cursor: pointer;"
                >
                  <el-tag size="medium">{{
                    $t('program.list.table.check')
                  }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="审核状态"
            align="center"
            key="examine"
            prop="examine"
            v-if="columns[9].visible"
          /> -->
          <!-- 创建时间 -->
          <el-table-column
            :label="$t('program.list.table.createTime')"
            align="center"
            prop="createTime"
            v-if="columns[10].visible"
            width="160"
            sortable
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column
            :label="$t('program.list.table.hanld')"
            align="center"
            width="100"
            class-name="small-padding fixed-width"
            v-if="columns[11].visible"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                plain
                icon="el-icon-edit"
				style="padding:6px 5px;"
				size='mini'
                @click="handleProgram(scope.row)"
                v-hasPermi="['lgsv:program:edit']"
              >
                {{ $t('program.list.table.edit') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <pagination
		ref='paginDom'
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getProgramList"
        />
      </el-col>
      <!-- 节目编辑组件 -->
    </el-row>
	<el-col v-show="!isShow" class="editBox">
	  <program-list
	    @show="getProgramList"
	    @changeBack="changeBacks"
	    :txt="editObj"
	    :text="panduan"
		:timeDon='timeMsagg'
	    :card="cardConfig"
	     v-if="flag"
	    :key="flags"
	  ></program-list>
	</el-col>
  </div>
</template>
<script>
import axios from "axios"
import Cookies from 'js-cookie'
import { mapState, mapMutations } from 'vuex'
import {
  programs,
  addProgram,
  delprogram,
  getCard,
  getDev,
  programsSend,
  pullProgram
} from '@/api/system/program' //获取节目列表
import { getToken } from '@/utils/auth' // 获取token
import { treeselect } from '@/api/system/dept' // 导入Tree树形Api
import Treeselect from '@riophae/vue-treeselect' // 导入Tree树形控件组件
import '@riophae/vue-treeselect/dist/vue-treeselect.css' // 导入Tree树形css样式
import programList from './editProgram/index.vue' // 导入编辑节目
import { checkPermi } from '@/utils/permission'
export default {
  name: 'ProgramList',
  components: { Treeselect, programList},
  data () {
    return {
	  editTimeArr: [{
	  	title: '年月日',
	  	options: [{
	  		id: 0,
	  		text: 'YYYY年MMMM月DDDD日',
	  		type:'%Y年%m月%d日'
	  	}, {
	  		id: 1,
	  		text: 'YY年MM月DD日',
	  		type:'%y年%m月%d日'
	  	}, {
	  		id: 2,
	  		text: 'YYYY-MMMM-DDDD',
	  		type:'%Y-%m-%d'
	  	}, {
	  		id: 3,
	  		text: 'YY-MM-DD',
	  		type:'%y-%m-%d'
	  	}, {
	  		id: 4,
	  		text: 'YYYY/MMMM/DDDD',
	  		type:'%Y/%m/%d'
	  	}, {
	  		id: 5,
	  		text: 'YY/MM/DD',
	  		type:'%y/%m/%d'
	  	}, {
	  		id: 6,
	  		text: 'YYYY.MMMM.DDDD',
	  		type:'%Y.%m.%d'
	  	}, {
	  		id: 7,
	  		text: 'YY.MM.DD',
	  		type:'%y.%m.%d'
	  	}]
	  }, {
	  	title: '时分秒',
	  	options: [{
	  		id: 0,
	  		text: 'HH时MM分SS秒',
	  		type:'%H时%M分%S秒'
	  	}, {
	  		id: 1,
	  		text: 'HH:MM:SS',
	  		type:'%H:%M:%S'
	  	}]
	  }, {
	  	title: '星期',
	  	options: [{
	  		id: 0,
	  		text: '',
	  		type:'星期%w'
	  	}]
	  }],
	  timeMsagg:[],
	  isTable:false,
	  tableHeight:0,
      // 遮罩层commit
      loading: true,
      expandedKeysed: [],
      // 选中数组
      ids: [],
      cards: [],
      cardList: undefined,
      defaultPropsd: {
        children: 'children',
        label: 'label'
      },
      cardConfig: undefined,
      filterText: '',
      isShow: true,
      editObj: undefined,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      sendShow: true,
      // 显示搜索条件
      showSearch: true,
      panduan: false,
      // 总条数
      total: 0,
      pullProgramConfig: {
        cardList: [],
        command: 47,
        idList: []
      },
      sendPull: 0,
      flag: false,
      flags: 0,
      expandedKeys: [], //默认打开的节点
      // 用户表格数据
      userList: [],
      dialogVisible: false,
      // 弹出层标题
      title: '',
      sendConfig: {
        cardList: [],
        idList: [],
		command:193
      },
	  panduanID:undefined,
      expireProgram: [],
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        pTitle: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
        pId: undefined
      },
      // 查询设备参数
      quer2: {
        deptId: undefined
      },
      // 表格列信息
      columns: [
        { key: 0, label: `节目ID`, visible: true },
        { key: 1, label: `节目号`, visible: true },
        { key: 2, label: `节目名称`, visible: true },
        { key: 3, label: `节目类型`, visible: true },
        { key: 4, label: `所属组织`, visible: true },
        { key: 5, label: `播放开始日期`, visible: true },
        { key: 6, label: `播放结束日期`, visible: true },
        { key: 7, label: `分区数量`, visible: true },
        { key: 8, label: `节目内容`, visible: true },
        { key: 9, label: `审核状态`, visible: true },
        { key: 10, label: `时间`, visible: true },
        { key: 11, label: `操作`, visible: true }
      ],
	  allDev:0,
	  seleteDev:0,
	  timeSearch:undefined
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName (val) {
      this.$refs.tree.filter(val)
    },
  //   filterText (val) {
	 //  console.log(val)
	 //  clearTimeout(this.timeSearch)
	 //  let that=this
	 //  this.timeSearch=setTimeout(function(){
		// that.$refs.tree2.filter(val) 
		// console.log(100)
	 //  },1000) 
      
  //   },
    deptOptions: {
      handler () {
        this.deptOptions.forEach(item => {
          this.expandedKeysed.push(item.id)
        })
      },
      deep: true
    },
    cardList: {
      handler () {
        this.cardList.forEach(item => {
          this.expandedKeys.push(item.id)
		  
        })
      },
      deep: true
    },
	"$store.state.deptId": {
	      handler(newval) {
			this.flag = false
			this.queryParams.deptId = newval
			this.quer2.deptId = newval
			this.panduanID=true
			this.seleteDev=0
			this.getProgramList() //查询节目列表
	      }
	}
  },
  created () {
	this.queryParams.deptId=this.$store.state.deptId
	this.quer2.deptId=this.$store.state.deptId
	this.panduanID=true
    // this.getTreeselect() //下拉树
    this.getProgramList() //查询节目列表
    this.getAllprogram() //查询所有过期节目
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msg
    })
	if(Cookies.get('Access_token')){
		return
	}else{
		axios({
		  url:process.env.VUE_APP_HUO_QU,
		  method: 'post',
			headers:{
				'Content-Type': 'application/x-www-form-urlencoded',
				'Access-Control-Allow-Origin': '*',
				"access-control-allow-credentials": "true"
			}
		}).then(res=>{
			console.log(res)
			Cookies.set('Access_token', res.data.access_token, { expires: 28 })//cookie保存时间
		}).catch(function (error) {
			console.log(error);
		});
	}
  },
  mounted(){
	this.tableHeight=(this.$refs.consDom.offsetHeight-this.$refs.colDom.offsetHeight-100)
	this.isTable=true
	this.getTime()
  },
  methods: {
    checkPermi,
	searchTree(){
		this.$refs.tree2.filter(this.filterText) 
	},
		getTime(){
			const now = new Date()
			const date = {
				year: now.getFullYear(), // 获取完整的年份 2019
				month: now.getMonth() + 1, //获取当前月份(0-11,0代表1月)
				date: now.getDate(), //获取当前日(1-31)
				day: now.getDay(), //获取当前星期X(0-6,0代表星期天)
				hours: now.getHours(), //获取当前小时数(0-23)
				min: now.getMinutes(), //获取当前分钟数(0-59)
				sec: now.getSeconds(), //获取当前秒数(0-59)
			}
			const newmonth = date.month >= 10 ? date.month : '0' + date.month
			const newdate = date.date >= 10 ? date.date : '0' + date.date
			const newhours = date.hours >= 10 ? date.hours : '0' + date.hours
			const newmin = date.min >= 10 ? date.min : '0' + date.min
			const newsec = date.sec >= 10 ? date.sec : '0' + date.sec
			let newday = date.day
			let dayCycleArray = ["日", "一", "二", "三", "四", "五", "六"];
			for (let i = 0; i < 7; i++) {
				if (date.day == i) {
					newday = dayCycleArray[i];
				}
			}
			let bianYear = date.year - 2000
			this.editTimeArr[0].options[0].text = date.year + '年' + newmonth + '月' + newdate + '日'
			this.editTimeArr[0].options[1].text = bianYear + '年' + newmonth + '月' + newdate + '日'
			this.editTimeArr[0].options[2].text = date.year + '-' + newmonth + '-' + newdate
			this.editTimeArr[0].options[3].text = bianYear + '-' + newmonth + '-' + newdate
			this.editTimeArr[0].options[4].text = date.year + '/' + newmonth + '/' + newdate
			this.editTimeArr[0].options[5].text = bianYear + '/' + newmonth + '/' + newdate
			this.editTimeArr[0].options[6].text = date.year + '.' + newmonth + '.' + newdate
			this.editTimeArr[0].options[7].text = bianYear + '.' + newmonth + '.' + newdate
			this.editTimeArr[1].options[0].text = newhours + '时' + newmin + '分' + newsec + '秒'
			this.editTimeArr[1].options[1].text = newhours + ':' + newmin + ':' + newsec
			this.editTimeArr[2].options[0].text = '星期' + newday
		},
	// 在线离线不同颜色显示
	renderContent(h, {node,data,store}) {
		{{
			if (data.isOnline == 0) {
				return <span style = "color:red" > {node.label} < /span>;
			} else if (data.isOnline == 1) {
				return <span style = "color:#228B22" > {node.label} < /span>;
			} else {
				return <span style = "color:#000" > {node.label} < /span>;
			}
		}}
	},	
    // 查询所有即将过期节目
    getAllprogram () {
      programs(
        this.addDateRange({ deptId: this.queryParams.deptId }, this.dateRange)
      ).then(response => {
        if (response.code == 200) {
          const nowDate = new Date()
          const date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate()
          }
          let arr = []
          const newmonth = date.month >= 10 ? date.month : '0' + date.month
          const day = date.date >= 10 ? date.date : '0' + date.date
          let updateTime = parseInt(date.year + newmonth + day)
          for (let i = 0; i < response.rows.length; i++) {
            let endTime = parseInt(response.rows[i].endTime.replace(/-/g, ''))
            if (updateTime == endTime - 1 || updateTime == endTime) {
              arr.push(response.rows[i].pId)
            }
          }
          if (arr.length > 0) {
            this.$message({
				showClose: true,
              message: '节目ID为' + arr + '的节目即将到期',
              type: 'warning'
            })
          }
        } else {
          console.log(400)
        }
      })
    },
    getProgramContent (row, column, cell, event) {
      this.isprogramContent = true
    },
    // 查询节目列表
    getProgramList () {
      this.loading = true
      this.isShow = true
      programs(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          if (response.code == 200) {  
            this.userList = response.rows
            for (let i = 0; i < this.userList.length; i++) {
              this.userList[i].startTime = this.userList[i].startTime.substring(0,11)
              this.userList[i].endTime = this.userList[i].endTime.substring(0,11)
			  for(let j=0;j<this.userList[i].lgProgramAreaList.length;j++){
				if(this.userList[i].lgProgramAreaList[j].areaType==6){
					this.userList[i].lgProgramAreaList[j].lgProgramMaterialList[0].lgFile.createBy=this.userList[i].lgProgramAreaList[j].lgProgramMaterialList[0].mMessage
					this.userList[i].lgProgramAreaList[j].lgProgramMaterialList[0].mMessage=this.userList[i].lgProgramAreaList[j].lgProgramMaterialList[0].mMessage.split('?|?')[0]
					for(let k=0;k<this.editTimeArr.length;k++){
						for(let z=0;z<this.editTimeArr[k].options.length;z++){
							this.userList[i].lgProgramAreaList[j].lgProgramMaterialList[0].mMessage=this.userList[i].lgProgramAreaList[j].lgProgramMaterialList[0].mMessage.replace(this.editTimeArr[k].options[z].type,this.editTimeArr[k].options[z].text)
						}
					}
				}
			  }			
            }
            this.total = response.total
            this.loading = false
          } else {
            console.log(400)
          }
        }
      )
    },
    // 时间过期标红提示
    tableRowClassName ({ row, rowIndex }) {
      const nowDate = new Date()
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      }
      const newmonth = date.month >= 10 ? date.month : '0' + date.month
      const day = date.date >= 10 ? date.date : '0' + date.date
      let updateTime = parseInt(date.year + newmonth + day)
      let endTime = parseInt(row.endTime.replace(/-/g, ''))
      if (updateTime == endTime - 1 || updateTime == endTime) {
        return 'warning-row'
      } else if (updateTime > endTime) {
        return 'success-row'
      } else {
        return ''
      }
      return ''
    },
    // 发送节目设备下拉树
    filterNodes (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    changeBacks (val) {
      this.isShow = val
    },
	// 设备过多时分段发送
	// devList(arr){
	// 	return new Promise((resolve,reject)=>{
	// 		let temp = []
	// 		arr.map(item => {
	// 			return temp.push(item)
	// 		})
	// 		const num = 3
	// 		// Math.ceil()  “向上取整”， 即小数部分直接舍去，并向正数部分进1
	// 		const parts = Math.ceil(arr.length / num)
	// 		const newArr = []
	// 		for (let i = 0; i <= parts; i++) {
	// 			if (i * num >= arr.length) {
	// 				break
	// 			}
	// 			newArr.push(temp.slice(i * num, (i + 1) * num))
				
	// 		}
	// 		resolve(newArr)
	// 	}).then(res=>{
	// 		this.devCallBack(res,0)
	// 	})
	// },
	// 发送的回调
	// devCallBack(arr,i){
	// 	if(i<arr.length){
	// 		programsSend({
	// 			cardList: arr[i],
	// 			idList:this.sendConfig.idList
	// 		}).then(res => {
	// 		  if (res.code == 200) {
	// 		    this.devCallBack(arr,i+1)
	// 		  }
	// 		})
	// 	}else{
	// 		this.$message.success(res.msg)
	// 	}
		
	// },
    // 发送设备与下架设备
    seedDev () {
		 this.dialogVisible = false
		 if (this.sendPull == 1) {
		    this.$refs.tree2.getCheckedNodes(true).forEach(item => {
		       if (item.id.length > 8) {
		          this.sendConfig.cardList.push(item.id)
		       }
		    })
		    this.$refs.tree2.setCheckedKeys([])
		 	programsSend(this.sendConfig).then(res => {
		 	  if (res.code == 200) {
		 	    this.$message.success(res.msg)
					this.sendConfig.cardList=[]
					this.seleteDev=0
		 		// this.panduanID=true
		 	  }
		 	})		
		 } else if (this.sendPull == 2) {
		   this.$refs.tree2.getCheckedNodes(true).forEach(item => {
		     if (item.id.length > 5) {
		       this.pullProgramConfig.cardList.push(item.id)
		     }
		   })
		   this.$refs.tree2.setCheckedKeys([])
		   pullProgram(this.pullProgramConfig).then(res => {
		     if (res.code == 200) {
		       this.pullProgramConfig.cardList = []
		       this.pullProgramConfig.idList = []
		 	   this.seleteDev=0
		       this.$message.success('节目下架中')
		     } else {
		       // this.pullProgramConfig.cardList = []
		       // this.pullProgramConfig.idList = []
		       this.$message.error(res.msg)
		     }
		   })
		 }
      
    },
    // 节目下架
    handPull () {
      this.pullProgramConfig.idList = this.cards
      this.dialogVisible = true
      this.sendPull = 2
	  if(this.panduanID){
		getDev(this.quer2).then(res => {
			if(res.code==200){
				console.log(100)
				this.cardList = res.data
				this.allDev=0
				this.forDevTree(res.data)
				this.panduanID=false
			}
		  
		})
	  }
      
    },
    handExpire () {
      programs(
        this.addDateRange({ deptId: this.queryParams.deptId }, this.dateRange)
      ).then(response => {
        if (response.code == 200) {
          const nowDate = new Date()
          const date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            date: nowDate.getDate()
          }
          let arr = []
          const newmonth = date.month >= 10 ? date.month : '0' + date.month
          const day = date.date >= 10 ? date.date : '0' + date.date
          let updateTime = parseInt(date.year + newmonth + day)
          for (let i = 0; i < response.rows.length; i++) {
            let endTime = parseInt(response.rows[i].endTime.replace(/-/g, ''))
            if (updateTime > endTime) {
              response.rows[i].startTime = response.rows[i].startTime.substring(
                0,
                11
              )
              response.rows[i].endTime = response.rows[i].endTime.substring(
                0,
                11
              )
              arr.push(response.rows[i])
            }
          }
          this.userList = arr
        } else {
          console.log(400)
        }
      })
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleShebeiClick (data,pro) {
		this.seleteDev=0
      pro.checkedKeys.forEach(item => {
        if (item.length > 8) {
          this.seleteDev++
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1 //搜索从第一页开始显示
      this.getProgramList() //查询节目列表
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.pId)
      this.cards = selection.map(item => item.pNo)
      this.multiple = !selection.length
      this.sendShow = !selection.length
    },
    /** 新增按钮操作 */
  //   handleAdd () {
  //     this.reset()
  //     this.getTreeselect()
  //     getUser().then(response => {
  //       this.postOptions = response.posts
  //       this.roleOptions = response.roles
  //       this.open = true
		// console.log(response)
  //       this.title = '新增设备'
  //     })
  //   },
    /** 删除按钮操作 */
    handleDelete (row) {
      const userIds = row.pId || this.ids
      let that = this
      this.$confirm('确定要删除选中的数据吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        delprogram(userIds).then(res => {
          if (res.code == 200) {
            that.getProgramList() //查询节目列表
            that.flag = false
            that.msgSuccess('删除成功')
          } else if (res.code == 409) {
            let arr = []
            res.data.forEach(item => {
              arr.push(item.PId)
            })
            that.$message({
				showClose: true,
              message:'节目ID为' + arr + '的节目当前有设备使用，请下架后再删除',
              type: 'warning'
            })
          }
        })
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return exportUser(queryParams)
        })
        .then(response => {
          this.download(response.msg)
        })
    },
    //发送节目进入按钮
    handleImport () {
      // this.sendConfig.cardList = []
      this.sendConfig.idList = this.ids
      this.dialogVisible = true
      this.sendPull = 1
	  if(this.panduanID){
			getDev(this.quer2).then(res => {
				if(res.code==200){
					console.log(100)
					this.cardList = res.data
					this.allDev=0
					this.forDevTree(res.data)
					this.panduanID=false
				} 
			}) 
	  }
      
    },
	// 递归获取设备数量
	forDevTree(obj) {
		for (let i = 0; i < obj.length; i++) {
			if (obj[i].id.length > 8) {
				this.allDev++
			}
			if (obj[i].children) {
				this.forDevTree(obj[i].children)
			}
		}
	},
    handleClose (done) {
      done()
    },
    //新增节目按钮
    handleUpdateEdit () {
      this.isShow = false
      this.flag = true
      this.panduan = false
      getCard(this.queryParams.deptId).then(res => {
        this.cardConfig = res.data
      })
      this.flags++
    },
    //编辑节目按钮
    handleProgram (data) {
      this.editObj = data
      getCard(this.editObj.deptId).then(res => {
        this.cardConfig = res.data
      })
      this.isShow = false
      this.flag = true
      this.panduan = true
      this.flags++
    },
	handleProgramId(data){
		this.$store.commit('updateProgramPid',data.pId)
		this.$router.push({  //核心语句
		    path:'./equipmentAds',   //跳转的路径 
			 query:{           //路由传参时push和query搭配使用 ，作用时传递参数
			  id:'pro', 
			}
		})
	}
  }
}
</script>
<style lang="scss" scoped="scoped">
.editBox {
  width: 100%;
  // border: 1px solid red;
  background-color: blanchedalmond;
  height: 100%;
  // padding: 10px;
}
::v-deep.app-container {
	// padding: 0;
	width: 100%;
	height: 100%;
  .el-table .success-row {
    color: red !important;
  }
  .el-table .warning-row {
    color: #ebb563 !important;
  }
  .mytree {
    position: relative;
    .el-dialog__header {
      background: cadetblue;
      text-align: left;
    }
    .el-dialog__footer {
      position: absolute;
      top: 0;
      right: 50px;
    }
    .el-dialog__body {
      height: 82vh;
      padding: 10px 30px;
      .el-tree {
        padding: 10px;
        height: 100%;
        .el-tree-node {
          height: 100%;
          .el-tree-node__content {
            height: 22px;
          }
        }
      }
    }
  }
}
</style>
